package cn.wolfcode.rbac.springsecurity.filter;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.utils.JwtUtils;
import cn.wolfcode.rbac.utils.RedisUtils;
import cn.wolfcode.rbac.utils.SecurityUtils;
import cn.wolfcode.rbac.web.exception.BusinessException;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static cn.wolfcode.rbac.common.RedisKeyPrefix.LOGIN_EMPLOYEE_PREFIX;

@Component
public class JwtAuthenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 每次发起请求接口都会经过该过滤器，判断是否已经登录
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.从请求头获取token
        String token = request.getHeader(jwtUtils.getHeader());
        if(!StringUtils.isEmpty(token)){
            //2.解析token,获取uuid
            String uuid = jwtUtils.getPayload(token, "uuid");
            //3.根据uuid，从redis中获取employee用户信息
            String employeeJson = redisUtils.get(LOGIN_EMPLOYEE_PREFIX + uuid);
            if (!StringUtils.isEmpty(employeeJson)) {
                Employee employee = JSON.parseObject(employeeJson, Employee.class);
                //4.如果有用户信息，则添加到上下文中
                SecurityUtils.setSecurityContextByUsernameAndPassword(employee.getName(), employee.getPassword());
            }
        }
        //5.放行
        filterChain.doFilter(request,response);
    }
}
